package com.xiaoxie.common.utils;

import com.xiaoxie.common.constant.Constants;
import com.xiaoxie.common.union.R;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiaoxie
 * @create 2025-01-19
 * @Version 1.0。0
 * @Description: Response工具类
 */
@Slf4j
public class ResponseUtils {

    /**
     * 把json字符串写入到响应中
     * @param response 响应对象
     * @param JsonStr 写入的json字符串
     */
    public static void write(HttpServletResponse response, String JsonStr) {
        if (response == null) {
            log.error("响应对象为空，无法写入响应对象");
            throw new IllegalArgumentException("响应对象为空");
        }
        writeInternal(response, JsonStr);
    }

    /**
     * 把R对象写入到响应中
     * @param response 响应对象
     * @param r 统一返回对象
     */
    public static void write(HttpServletResponse response, R r) {
        if (response == null) {
            log.error("响应对象为空，无法写入响应对象");
            throw new IllegalArgumentException("响应对象为空");
        }
        if (r == null) {
            log.error("返回对象为空，无法写入响应对象");
            throw new IllegalArgumentException("返回对象为空");
        }
        writeInternal(response, JSONUtils.toJson(r));
    }

    /**
     * 内部方法，用于将字符串写入响应对象
     * @param response 响应对象
     * @param jsonStr 写入的json字符串
     */
    private static void writeInternal(HttpServletResponse response, String jsonStr) {
        response.setContentType(Constants.JSON_RESPONSE_CONTENT_TYPE);
        try (PrintWriter out = response.getWriter()) {
            out.println(jsonStr);
            out.flush();
        } catch (IOException e) {
            log.error("写入响应对象失败", e);
            throw new RuntimeException("写入响应对象失败", e);
        }
    }
}
